﻿using System;
using System.Collections.Generic;
using System.Linq;
using Framework.Exceptions.RepositoryExceptions;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.UserRoleModels;

namespace SQLRepositories.UserRoleRepositories
{
    public class SessionRepository : EntityBaseRepository<SessionModel>, ISessionRepository
    {
        public SessionRepository(IDBEconomicInformationServiceContext context) 
            : base(context)
        {}

        public void Create(SessionModel item)
        {
            Context.Sessions.Add(item);
            Context.SaveChanges();
        }

        public SessionModel GetById(Guid id)
        {
            return Context.Sessions.FirstOrDefault(x => x.Id.Equals(id));
        }

        public void Delete(Guid id)
        {
            var removedItem = Context.Sessions.FirstOrDefault(x => x.Id.Equals(id));
            if(removedItem == null)
                throw new EntityNotFoundException("Session");
            Context.Sessions.Remove(removedItem);
            Context.SaveChanges();
        }

        public void Delete(SessionModel item)
        {
            Context.Sessions.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<SessionModel> GetAll()
        {
            return Context.Sessions;
        }

        public SessionModel GetByUserId(Guid userId)
        {
            return (from session in Context.Sessions
                   where session.User.Id.Equals(userId) 
                   orderby session.ChangedDate select session)
                   .FirstOrDefault();
        }
    }
}
